import React, { useEffect, useLayoutEffect, useState } from "react";
import { Badge, TabBar } from "antd-mobile";
import {
  AppOutline,
  UnorderedListOutline,
  UserOutline,
} from "antd-mobile-icons";
import styles from "./index.module.scss";
import { useLocation, useNavigate } from "react-router-dom";

type Props = {};

export default function index({}: Props) {
  const tabs = [
    {
      key: "home",
      title: "首页",
      icon: <AppOutline />,
      path: "/",
    },
    {
      key: "quick",
      title: "快速刷题",
      icon: <UnorderedListOutline />,
      path: "/quick",
    },
    {
      key: "user",
      title: "我的",
      icon: <UserOutline />,
      path: "/user",
    },
  ];
  const [activeKey, setActiveKey] = useState("/"); //key值
  const navigate = useNavigate(); //跳转
  const location = useLocation(); //获取路径
  const [show, setShow] = useState<boolean>(false); //是否隐藏tabbar

  useLayoutEffect(() => {
    let index = tabs.findIndex((item) => item.path == location.pathname);
    if (index !== -1) {
      setActiveKey(tabs[index].key);
      setShow(true);
    } else {
      setShow(false);
    }
  }, [location.pathname]);

  // useEffect(() => {
  //   navigate(activeKey);
  // }, [activeKey]);
    // 当tabbar被点击的时候
    const change = (e: string) => {
      // 设置高亮
      setActiveKey(e);
      // 跳转
      let index = tabs.findIndex((item) => item.key === e);
      navigate(tabs[index].path);
    }
  return (
    <TabBar
      style={{
        display: show ? "block" : "none",
      }}
      activeKey={activeKey}
      onChange={change}
      safeArea={true}
      className={styles.qd_tabbar}
    >
      {tabs.map((item) => (
        <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
      ))}
    </TabBar>
  );
}
